"""
题目：返回第 n 个节点的值，位置无效返回 None。
"""

class Node:
    def __init__(self, val=0, prev=None, next=None):
        self.val = val
        self.prev = prev
        self.next = next

def get_val_at_position(head, pos):
    """获取双链表第pos个节点的值（1开始）"""
    if pos < 1 or head is None:
        return None
    current = head
    # 移动pos-1次到达目标位置
    for _ in range(pos - 1):
        current = current.next
        if current is None:
            return None  # 位置超出范围
    return current.val

def create_doubly_linked_list(arr):
    if not arr:
        return None
    head = Node(arr[0])
    current = head
    for val in arr[1:]:
        new_node = Node(val)
        current.next = new_node
        new_node.prev = current
        current = new_node
    return head

# 测试
if __name__ == "__main__":
    head = create_doubly_linked_list([10, 20, 30, 40])
    print(get_val_at_position(head, 2))  # 输出: 20
    print(get_val_at_position(head, 5))  # 输出: None（位置无效）
    print(get_val_at_position(head, 0))  # 输出: None（位置无效）